package cc.linker.steplink.crm.merchant.task;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.merchant.dao.PersonnelDao;
import cc.linker.steplink.crm.merchant.util.SpringUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;

/**
 * 异步发送邮件的线程
 */
@Component
@Data
@NoArgsConstructor
@Slf4j
public class EmailSendCallable implements Callable<Integer> {

    PersonnelDao personnelDao = SpringUtils.getBean("personnelDao");
    Environment environment = SpringUtils.getBean("environment");

    // 构造参数
    private String email;
    private String content;
    private String taskName;
    private String orgId;
    private String taskId;

    public EmailSendCallable(String email, String content, String taskName, String orgId, String taskId) {
        this.email = email;
        this.content = content;
        this.taskName = taskName;
        this.orgId = orgId;
        this.taskId = taskId;
    }

    @Override
    public Integer call() {

        Integer successCount = Integer.valueOf(0);
        // 使用工具类获取配置文件属性

        String stepLinkHdUrl = environment.getProperty("system.scrm.stepLinkUrl");
        String demoEmailFrom = environment.getProperty("test.mail.username");
        LOGGER.info("--------stepLinkHdUrl： " + stepLinkHdUrl);

        // 构造传递的参数
        Map<String, Object> map = new HashMap<>();
        map.put("senStatus", 1);
        map.put("email", email);
        map.put("sendStatus", 1);
        map.put("sendTime", new Date());
        map.put("createTime", new Date());
        map.put("taskId", taskId);
        map.put("taskName", taskName);

        // 数据常量
        String mailPrefix = Constants.WXQrCodeMail.MAIL_PREFIX;
        String orgNotice = Constants.WXQrCodeMail.ORG_NOTICE;
        String task = Constants.WXQrCodeMail.TASK_ID_NOTICE;

        //如果没有二维码标识 orgId置isNull => 后续不会根据orgId查询二维码token(不生成二维码)
        if (!org.apache.commons.lang.StringUtils.contains(content, Constants.WXQrCodeMail.QRCODE_NOTICE)) {
            orgId = "isNull";
        }else{
            content = content.replace(Constants.WXQrCodeMail.QRCODE_NOTICE, "");
        }
        //跳转邮件参数规则
        String parms = mailPrefix + email + orgNotice + orgId + task + taskId;

        //邮件正文HTML部分
        String contentHtml = "<br/><img src='" + stepLinkHdUrl + "/redirect/emailReadRedirect/" + parms + "'>";

        try {
            LOGGER.info("开始发送邮件=====当前邮箱为：" + email);
            //通过sender对象设置邮件相关配置信息
            JavaMailSenderImpl sender = new JavaMailSenderImpl();

            //创建一个邮件体
            MimeMessage mimeMessage = createMineMessage(sender);

            //第二个参数true表示使用HTML语言来编写邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            //发件人邮件地址(上面获取到的，也可以直接填写,string类型)
            helper.setFrom(demoEmailFrom);

            //收件人邮件地址
            helper.setTo(email);

//            //抄送自己
//            helper.setCc(demoEmailFrom);

            //邮件主题
            helper.setSubject(taskName);

            //邮件正文,
            helper.setText(content + contentHtml, true);

            //发送邮件
            LOGGER.info("开始发送至目标邮箱： " + email);
            LOGGER.info("开始发送至目标邮箱demoEmailFrom： " + demoEmailFrom);
            LOGGER.info("开始发送至目标邮箱taskName： " + taskName);
            LOGGER.info("开始发送至目标邮箱content： " + content);
            sender.send(mimeMessage);
            LOGGER.info("当前邮件发送完毕=================");
            successCount = 1;
        } catch (Exception e) {
            LOGGER.info("发送邮件异常：" + e);
            map.put("sendStatus", 2);
            map.put("TaskName", taskName);
            successCount = 0;
        }
        //添加至任务中
        personnelDao.addEmailTask(map);
        return successCount;
    }

    //设置邮件授权信息
    public MimeMessage createMineMessage(JavaMailSenderImpl sender) {
        String demoEmailFrom = environment.getProperty("test.mail.username");
        String demoEmailToken = environment.getProperty("test.mail.password");
        String demoEmailHost = environment.getProperty("test.mail.host");
        String demoEmailPort = environment.getProperty("test.mail.port");

        sender.setHost(demoEmailHost);//邮箱地址
        sender.setUsername(demoEmailFrom);//对应邮箱的用户名
        sender.setPassword(demoEmailToken);//密码
        sender.setPort(Integer.valueOf(demoEmailPort));//端口

        LOGGER.info("设置邮件授权信息demoEmailHost： " + demoEmailHost);
        LOGGER.info("设置邮件授权信息demoEmailFrom： " + demoEmailFrom);
        LOGGER.info("设置邮件授权信息demoEmailToken： " + demoEmailToken);
        LOGGER.info("设置邮件授权信息demoEmailPort： " + demoEmailPort);
        sender.setDefaultEncoding(StandardCharsets.UTF_8.toString());//邮件编码方式

        Properties properties = new Properties();
        properties.put(Constants.EmailPropertiesCode.PROPERTIES_EMAIL_HOST, demoEmailHost);
        properties.put(Constants.EmailPropertiesCode.PROPERTIES_EMAIL_AG, Constants.EmailPropertiesCode.PROPERTIES_EMAIL_SSL);//设置为SSL协议
        properties.put(Constants.EmailPropertiesCode.PROPERTIES_EMAIL_AUTU, Constants.BooleStr.FALSE);//是否需要开启邮箱验证
        properties.put(Constants.EmailPropertiesCode.PROPERTIES_EMAIL_PORT, Integer.valueOf(demoEmailPort));//端口
        properties.put(Constants.EmailPropertiesCode.PROPERTIES_EMAIL_TIMEOUT, "5000");//端口
        properties.put("mail.debug", false);
        properties.put("mail.smtp.socketFactory.port", Integer.valueOf(demoEmailPort));
        sender.setJavaMailProperties(properties);
        return sender.createMimeMessage();

    }
}
